<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { getVerifiCode, verifiCodeCheck, modifyPasswordByPhone } from '@/api/login'
import { ElForm, ElFormItem, ElInput, ElMessage } from 'element-plus'
import CaptchaGenerator from '@/components/CaptchaGenerator/index.vue'
import { InputPassword } from '@/components/InputPassword'

const emit = defineEmits(['to-login'])

const { t } = useI18n()

const form: any = reactive({
  phone_num: '',
  captcha: '',
  code: '',
  password: '',
  checkPassword: '',
  unlock_ticket: ''
})
const isLoading = ref(false)
const captchaText = ref('')
const generatorRef = ref()
const formEl = ref()
const step = ref(0)
const time = ref(0)
let interval: any

const validateCaptcha = (_rule: any, value: any, callback: any) => {
  if (value.toLowerCase() != captchaText.value.toLowerCase()) {
    callback(new Error('请输入正确的图形验证码'))
  } else {
    callback()
  }
}
const validatePhone = (_rule: any, value: any, callback: any) => {
  if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}
const validatePassword2 = (_rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入确认密码'))
  } else if (value !== form.password) {
    callback(new Error('两次密码输入不一致'))
  } else {
    callback()
  }
}
const rules = reactive({
  phone_num: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入图形验证码', trigger: 'blur' },
    { validator: validateCaptcha, trigger: 'blur' }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      min: 6,
      message: '密码不能少于6位',
      trigger: 'blur'
    }
  ],
  checkPassword: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    { validator: validatePassword2, trigger: 'blur' }
  ]
})

const toLogin = () => {
  emit('to-login')
}

const initTime = () => {
  time.value = 60
  if (interval) {
    clearInterval(interval)
  }
  interval = setInterval(() => {
    time.value -= 1
    if (time.value === 0 && interval) {
      clearInterval(interval)
    }
  }, 1000)
}

// 再次发送
const resendSignCode = () => {
  isLoading.value = true
  getVerifiCode({
    phone_num: form.phone_num
  })
    .then(() => {
      initTime()
    })
    .finally(() => {
      isLoading.value = false
    })
}

// 获取手机验证码
const getSignCode = () => {
  formEl.value.validate((valid) => {
    if (valid) {
      isLoading.value = true
      getVerifiCode({
        phone_num: form.phone_num
      })
        .then(() => {
          initTime()
          step.value = 1
        })
        .finally(() => {
          isLoading.value = false
        })
    } else {
    }
  })
}
// 提交验证码
const verifiSignCode = () => {
  formEl.value.validate((valid) => {
    if (valid) {
      isLoading.value = true
      verifiCodeCheck({
        phone_num: form.phone_num,
        code: form.code
      })
        .then((res) => {
          form.unlock_ticket = res.data.unlock_ticket
          step.value = 2
        })
        .finally(() => {
          isLoading.value = false
        })
    } else {
    }
  })
}
// 修改密码
const resetSignCode = () => {
  formEl.value.validate((valid) => {
    if (valid) {
      isLoading.value = true
      modifyPasswordByPhone({
        phone_num: form.phone_num,
        password: form.password,
        unlock_ticket: form.unlock_ticket
      })
        .then(() => {
          toLogin()
          ElMessage.success('密码修改成功，请重新登录')
        })
        .finally(() => {
          isLoading.value = false
        })
    } else {
    }
  })
}
</script>

<template>
  <div style="width: 100%; padding: 20px" v-loading="isLoading">
    <ElForm
      ref="formEl"
      label-position="top"
      size="large"
      :model="form"
      :rules="rules"
      v-if="step === 1"
    >
      <ElFormItem>
        <h2 class="text-2xl font-bold text-center w-[100%]">请输入手机验证码</h2>
        <div class="text-center w-[100%]" style="color: #929aab">&nbsp;</div>
      </ElFormItem>
      <ElFormItem label="手机号">
        <ElInput v-model="form.phone_num" disabled />
      </ElFormItem>
      <ElFormItem label="手机验证码" prop="code">
        <div class="flex items-center">
          <ElInput v-model="form.code" placeholder="请输入手机验证码" />
          <div style="width: 5px"></div>
          <el-tag type="info" style="width: 50px" v-if="time">{{ time }}</el-tag>
          <el-link
            v-else
            style="line-height: 25px; width: 90px"
            size="small"
            @click="resendSignCode"
            >再次发送</el-link
          >
        </div>
      </ElFormItem>
      <ElFormItem>
        <div class="w-[100%]">
          <ElButton :loading="isLoading" type="primary" class="w-[100%]" @click="verifiSignCode">
            下一步
          </ElButton>
        </div>
      </ElFormItem>
    </ElForm>
    <ElForm
      ref="formEl"
      label-position="top"
      size="large"
      :model="form"
      :rules="rules"
      v-else-if="step === 2"
    >
      <ElFormItem>
        <h2 class="text-2xl font-bold text-center w-[100%]">设置新密码</h2>
        <div class="text-center w-[100%]" style="color: #929aab">&nbsp;</div>
      </ElFormItem>
      <ElFormItem label="新密码" prop="password">
        <InputPassword
          v-model="form.password"
          placeholder="请输入新密码"
          strength
          style="width: 100%"
        />
      </ElFormItem>
      <ElFormItem label="确认密码" prop="checkPassword">
        <InputPassword
          v-model="form.checkPassword"
          placeholder="请再次输入新密码"
          style="width: 100%"
        />
      </ElFormItem>
      <ElFormItem>
        <div class="w-[100%]">
          <ElButton :loading="isLoading" type="primary" class="w-[100%]" @click="resetSignCode">
            重置密码
          </ElButton>
        </div>
      </ElFormItem>
    </ElForm>
    <ElForm ref="formEl" label-position="top" size="large" :model="form" :rules="rules" v-else>
      <ElFormItem>
        <h2 class="text-2xl font-bold text-center w-[100%]">{{ t('login.retrievePassword') }}</h2>
        <div class="text-center w-[100%]" style="color: #929aab">验证码将会发送至你的注册手机</div>
      </ElFormItem>
      <ElFormItem label="手机号" prop="phone_num">
        <ElInput v-model="form.phone_num" placeholder="请输入手机号" />
      </ElFormItem>
      <ElFormItem label="验证码" prop="captcha">
        <div class="flex">
          <el-input v-model="form.captcha" placeholder="请输入验证码" />
          &nbsp;&nbsp;
          <CaptchaGenerator ref="generatorRef" v-model="captchaText" :length="4" />
        </div>
      </ElFormItem>
      <ElFormItem>
        <div class="w-[100%]">
          <ElButton :loading="isLoading" type="primary" class="w-[100%]" @click="getSignCode">
            {{ t('login.nextstep') }}
          </ElButton>
        </div>
      </ElFormItem>
    </ElForm>
    <el-link style="line-height: 25px" size="small" @click="toLogin">去登录</el-link>
  </div>
</template>

<style lang="less" scoped>
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}
</style>
